package panda.syntax;

import panda.query.condition.Clause;
import panda.query.condition.Sentence;
import aima.logic.propositional.parsing.ast.BinarySentence;
import aima.logic.propositional.parsing.ast.Symbol;

public class SentenceConvert {

	public static Sentence convert(aima.logic.propositional.parsing.ast.Sentence s) {
		Sentence sentence=new Sentence();
		processAnd(s, sentence);
		return sentence;
	}

	static void processAnd(aima.logic.propositional.parsing.ast.Sentence as, Sentence s){
		if (as instanceof BinarySentence) {
			BinarySentence bs = (aima.logic.propositional.parsing.ast.BinarySentence)as;
			if (bs.isAndSentence()) {
				processAnd(bs.getFirst(), s);
				processAnd(bs.getSecond(), s);
			}
			else {
				Clause c=new Clause();
				processOr(bs.getFirst(), c);
				processOr(bs.getSecond(), c);
				s.addClause(c);
			}
		}
		else if (as instanceof Symbol) {
			s.addClause(new Clause(((Symbol)as).getValue()));
		}
	}
	static void processOr(aima.logic.propositional.parsing.ast.Sentence b, Clause c) {
		if (b instanceof Symbol) {
			c.addClause(((Symbol)b).getValue());
		}
		else {
			processOr(((aima.logic.propositional.parsing.ast.BinarySentence)b).getFirst(), c);
			processOr(((aima.logic.propositional.parsing.ast.BinarySentence)b).getSecond(), c);
		}
	}


}
